package com.furkid.service.constant;

import com.furkid.service.config.QiniuConfig;
import com.furkid.service.domain.UploadResult;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;

@Component
public class QiniuUtil {

    private final QiniuConfig config;
    private final UploadManager uploadManager;

    public QiniuUtil(QiniuConfig config) {
        this.config = config;
        this.uploadManager = new UploadManager(new Configuration(Region.autoRegion()));
    }

    public UploadResult upload(MultipartFile file, String dir) throws IOException {
        if (file.isEmpty()) {
            throw new RuntimeException("文件为空");
        }

        String original = file.getOriginalFilename();
        String ext = "";
        if (original != null && original.contains(".")) {
            ext = original.substring(original.lastIndexOf("."));
        }

        String fileType = file.getContentType();
        long fileSize = file.getSize();

        // 目录示例：head/2025-11-14/uuid.jpg
        String key = dir + "/" + LocalDate.now() + "/" + UUID.randomUUID() + ext;

        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        String upToken = auth.uploadToken(config.getBucket());

        try {
            Response response = uploadManager.put(file.getBytes(), key, upToken);
            if (!response.isOK()) {
                throw new RuntimeException("七牛云错误：" + response.bodyString());
            }
        } catch (QiniuException e) {
            throw new RuntimeException("七牛云上传失败：" + e.error());
        }

        return new UploadResult(
                config.getDomain() + "/" + key,
                fileType,
                fileSize,
                key
        );
    }
}